package com.example.blogsystem.service;

import com.example.blogsystem.mapper.BlogInfoMapper;
import com.example.blogsystem.mapper.UserInfoMapper;
import com.example.blogsystem.model.BlogInfo;
import com.example.blogsystem.model.UserInfo;
import com.example.blogsystem.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Service
public class UserInfoService {

    @Autowired
    private BlogInfoMapper blogInfoMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;
    public UserInfo queryUserByName(String name) {
        return userInfoMapper.queryByUserName(name);
    }

    public UserInfo getUser(HttpServletRequest request) {
        //1.从token里面拿到用户id
        //2.然后进行查询拿到用户信息
        String jwt = request.getHeader("user_token");
        Integer id = JwtUtils.getUserId(jwt);
        if (id != null && id > 0) {
            return userInfoMapper.queryByUserId(id);
        }
        return null;
    }

    public UserInfo getAuthor(Integer id) {
        //1.根据文章id查询作者id
        //2.根据作者id查询作者信息
        BlogInfo blogInfo = blogInfoMapper.queryById(id);
        if(blogInfo == null) {
            log.error("根据id，未查询到文章");
            return null;
        }
        UserInfo userInfo = userInfoMapper.queryByUserId(blogInfo.getUserId());
        if(userInfo == null) {
            return null;
        }
        return userInfo;
    }

    public Integer registerUserInfo(UserInfo userInfo) {
        return userInfoMapper.registerUser(userInfo);
    }

    public Integer countUserInfo() {
        return userInfoMapper.countUser();
    }
}
